package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.cungmua.app.R;
import com.cungmua.app.adapter.CityPromotionEmailAdapter;
import com.cungmua.app.base.BaseDrawerActivitys;
import com.cungmua.app.handler.ChangeSubcriptionHandler;
import com.cungmua.app.handler.PaymentInfoHandler;
import com.cungmua.app.handler.ProfileHandler;
import com.cungmua.app.handler.RequestCityPromotionEmailHandler;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.CitySubcribe;
import com.cungmua.app.model.PaymentInfo;
import com.cungmua.app.model.ShippingAddress;
import com.cungmua.app.model.User;
import com.cungmua.app.model.request.ChangeSubcriptionRequest;
import com.cungmua.app.model.request.CityPromotionEmailRequest;
import com.cungmua.app.model.request.PaymentInfoRequest;
import com.cungmua.app.model.request.ProfileRequest;
import com.cungmua.app.model.response.ChangeSubcriptionResponse;
import com.cungmua.app.model.response.CityPromotionEmailResponse;
import com.cungmua.app.model.response.PaymentInfoResponse;
import com.cungmua.app.model.response.ProfileResponse;
import com.cungmua.app.task.ChangeSubcriptionTask;
import com.cungmua.app.task.PaymentInfoTask;
import com.cungmua.app.task.ProfileTask;
import com.cungmua.app.task.RequestCityPromotionEmailTask;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by kelvin.nguyen on 7/1/14.
 */
public class ProfileActivity extends BaseDrawerActivitys implements ProfileHandler,PaymentInfoHandler,RequestCityPromotionEmailHandler,ChangeSubcriptionHandler, View.OnClickListener {

    private TextView txtName;
    private TextView txtGender;
    private TextView txtBirthday;
    private TextView txtPhone;
    private TextView txtEmail;
    private TextView txtPhoneNumber;
    private TextView txtFullName;
    private TextView txtAddress;
    private TextView btnEdit;
    private TextView txtEdit;

    private TextView txtAddressType;


    private User user;
    private Button icon_cart;
    private ImageButton btnCreateAddress;
    private LinearLayout btnCart;
    private CityPromotionEmailAdapter mAdapter;
    private ListView listCitiesAcceptPromotions;
    private Spinner spinnerAddressReciver;
    private List<String> listShippingAddr = new ArrayList<String>();
    private List<ShippingAddress> listObShippingAddr = new ArrayList<ShippingAddress>();
    private PaymentInfo data;
    @Override
    public int getLayoutResource() {
        return R.layout.activity_profile;
    }

    @Override
    public void updateView() {
        User user = getCurrentUser();
        if (user.getId() == 0) {
            login();
            return;
        }
        ProfileRequest request = new ProfileRequest(getDeviceId(), getToken());
        request.setUserId(user.getId());
        ProfileTask task = new ProfileTask(this, this);
        task.execute(request);

        CityPromotionEmailRequest cityRequest=new CityPromotionEmailRequest(getDeviceId(),getToken());
        cityRequest.setUserId(String.valueOf(user.getId()));
        RequestCityPromotionEmailTask cityTask=new RequestCityPromotionEmailTask(this,this);
        cityTask.execute(cityRequest);

        PaymentInfoRequest requestPayment = new PaymentInfoRequest(getDeviceId(), getToken());
        requestPayment.setCityId(getCurrentCity().getId());
        requestPayment.setUserId(getCurrentUser().getId());

        PaymentInfoTask taskPayment = new PaymentInfoTask(this, this);
        taskPayment.execute(requestPayment);

    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        txtName = (TextView) findViewById(R.id.txtName);
        txtGender = (TextView) findViewById(R.id.txtGender);
        txtBirthday = (TextView) findViewById(R.id.txtBirthday);
        txtPhone = (TextView) findViewById(R.id.txtPhone);
        txtEmail = (TextView) findViewById(R.id.txtEmail);
        btnEdit = (TextView) findViewById(R.id.btnEdit);
        txtEdit = (TextView) findViewById(R.id.txtEdit);
        btnCart=(LinearLayout)findViewById(R.id.btnCart);
        icon_cart=(Button)findViewById(R.id.icon_cart);
        btnCreateAddress=(ImageButton)findViewById(R.id.btnCreateAddress);
        spinnerAddressReciver=(Spinner)findViewById(R.id.spinnerAddressReciver);
        listCitiesAcceptPromotions=(ListView)findViewById(R.id.listCitiesAcceptPromotions);

        txtFullName = (TextView) findViewById(R.id.txtFullName);
        txtPhoneNumber = (TextView) findViewById(R.id.txtPhoneNumber);
        txtAddress = (TextView) findViewById(R.id.txtAddress);
        txtAddressType = (TextView) findViewById(R.id.txtAddressType);

        btnEdit.setOnClickListener(this);
        txtEdit.setOnClickListener(this);
        btnCreateAddress.setOnClickListener(this);

        Cart currentCart=getCurrentCart();
        if(currentCart.getTotalQuantity()>0) {
            icon_cart.setText(currentCart.getTotalQuantity() + "");
            icon_cart.setVisibility(View.VISIBLE);
        }else{
            icon_cart.setVisibility(View.GONE);
        }

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToYourCart();
            }
        });

        spinnerAddressReciver.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                // getDistrictData(cityAdapter.getItem(i).getId());
                //Toast.makeText(getApplicationContext(),data.getAddressList().get(i).getCityName(),Toast.LENGTH_LONG).show();

                 updateAddressRecier(data.getAddressList().get(i));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    @Override
    public void onProfile(ProfileResponse profile) {
        if (profile.getCode() == 0) {
            user = profile.getData();
            txtName.setText(user.getName());
            txtGender.setText(user.getGender() == 0 ? getString(R.string.male) : getString(R.string.female));
            if(user.getDateOfBirth()!=null|!user.getDateOfBirth().toString().isEmpty()) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(user.getDateOfBirth());
                txtBirthday.setText("" + cal.get(Calendar.YEAR));
            }
            if(user.getMobile()!=null||!user.getMobile().toString().isEmpty())
                txtPhone.setText(user.getMobile());

            if(user.getEmail()!=null||!user.getEmail().toString().isEmpty())
                txtEmail.setText(user.getEmail());
            if(user.getFullTextAddress()!=null||!user.getFullTextAddress().toString().isEmpty())
                txtAddress.setText(user.getFullTextAddress());
        } else {
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setMessage(profile.getMessage())
                    .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnEdit:
                if (user != null)
                    editProfile(user);
                break;
            case R.id.btnCreateAddress:
                //go to Create Address Activity
                    if(user!=null)
                        gotoCreateAddress(data.getDefaultAddress());
                break;
            case R.id.txtEdit:
                    if(user!=null)
                        gotoEditAddress(data.getDefaultAddress());

                break;

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CREATE_ADDRESS) {
            if (resultCode == RESULT_OK) {
                refreshActivity();
            }
        }
    }
    @Override
    public void onListCityPromotionEmails(CityPromotionEmailResponse response) {
        if (response.getData() != null) {
            if (response.getData().size() > 0) {
                    mAdapter=new CityPromotionEmailAdapter(this,this,response.getData());
                    listCitiesAcceptPromotions.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
            } else {
                listCitiesAcceptPromotions.setEmptyView(findViewById(R.id.txtEmptyPastDeal));
            }
        }
    }

    @Override
    public void confirmPromotionEmail(final CitySubcribe citySubcribe) {
        final AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setTitle("Đăng ký nhận email");
        adb.setMessage("Bạn muốn nhận thông tin khuyến mãi từ "+citySubcribe.getCityName()+"?");
        adb.setPositiveButton("ĐỒNG Ý", new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
                // TODO Auto-generated method stub
                ChangeSubcriptionRequest changeSubcriptionRequest=new ChangeSubcriptionRequest(getDeviceId(),getToken());
                changeSubcriptionRequest.setUserId(getCurrentUser().getId());
                changeSubcriptionRequest.setCityId(citySubcribe.getCityID());
                ChangeSubcriptionTask changeSubcriptionTask=new ChangeSubcriptionTask(ProfileActivity.this,ProfileActivity.this);
                changeSubcriptionTask.execute(changeSubcriptionRequest);

            }
        });
        adb.setNegativeButton("BỎ QUA", null);
        adb.show();
    }

    @Override
    public void onPaymentInfo(PaymentInfoResponse response) {
        if(response.getCode()==0){
             data = response.getData();
            if (data.getAddressList().size() >= 1) {
                listShippingAddr = new ArrayList<String>();
                listObShippingAddr = new ArrayList<ShippingAddress>();
                for (ShippingAddress item : data.getAddressList()) {
                    listObShippingAddr.add(item);
                    String value = item.getAddressString() + " " + getString(R.string.phone_label, item.getPhone()
                            + " " + getString(R.string.receiver_label, item.getCustomerName()));
                    listShippingAddr.add(value);
                }
                ArrayAdapter<String> shippingListAdapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_dropdown_item);
                shippingListAdapter.addAll(listShippingAddr);
                spinnerAddressReciver.setAdapter(shippingListAdapter);
            }

            String valueAddress=data.getDefaultAddress().getAddressString() + " " + getString(R.string.phone_label, data.getDefaultAddress().getPhone()
                    + " " );

            txtAddress.setText(valueAddress);

            txtFullName.setText(data.getDefaultAddress().getCustomerName());
            txtPhoneNumber.setText(getString(R.string.dtdd_label, data.getDefaultAddress().getPhone()));

            String addressType=data.getDefaultAddress().getAddressType()==0?getString(R.string.label_address_type_home):getString(R.string.label_address_type_office);
            txtAddressType.setText(addressType);

        }else{
            alert(response.getMessage());
        }

    }
    public void updateAddressRecier(ShippingAddress address){
        String valueAddress=address.getAddressString() + " " + getString(R.string.phone_label, address.getPhone()
                + " " );

        txtAddress.setText(valueAddress);

        txtFullName.setText(address.getCustomerName());
        txtPhoneNumber.setText(getString(R.string.dtdd_label, address.getPhone()));

        String addressType=address.getAddressType()==0?getString(R.string.label_address_type_home):getString(R.string.label_address_type_office);
        txtAddressType.setText(addressType);
    }

    @Override
    public void onConfirmSubcription(ChangeSubcriptionResponse changeSubcriptionResponse) {
            refreshActivity();
           // alert(changeSubcriptionResponse.getMessage());
    }
}
